package servlets;

import com.restfb.Connection;
import com.restfb.DefaultFacebookClient;
import com.restfb.FacebookClient;
import com.restfb.json.JsonObject;
import com.restfb.types.User;
import ejb.FBuser;
import ejb.FBuserManager;
import ejb.SponsoredEventManager;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Antonio
 */
@WebServlet(name = "SlowMapsServlet", urlPatterns = {"/SlowMapsServlet"})
public class SlowMapsServlet extends HttpServlet {

    @EJB
    private SponsoredEventManager sponsoredEventManager;
    @EJB
    private FBuserManager FBuserManager;

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        HttpSession session = request.getSession();
        String accessToken = null,
                userId = null;
        try {
//            String maxLat = request.getParameter("max_lat");
//            String maxLng = request.getParameter("max_lat");
//            String minLat = request.getParameter("min_lat");
//            String minLng = request.getParameter("min_lng");
            String startDate = request.getParameter("from");
            String endDate = request.getParameter("to");
//            String city = request.getParameter("city");            

            // elaborazione delle date
            Calendar cal = Calendar.getInstance();
            DateFormat df = new SimpleDateFormat("dd/MM/yy");
            DateFormat df2 = new SimpleDateFormat("MM/dd/yyyy");
            Date sd;
            Date ed;
            // necessario per problemi di tipo
            try {
                ed = df.parse(endDate);
            } catch (ParseException ex) {
                ed = cal.getTime();
                Logger.getLogger(MapsServlet.class.getName()).log(Level.SEVERE, null, ex);
            }
            try {
                sd = df.parse(startDate);
            } catch (ParseException ex) {
                sd = cal.getTime();
                Logger.getLogger(MapsServlet.class.getName()).log(Level.SEVERE, null, ex);
            }


            userId = session.getAttribute("userid").toString();
            accessToken = session.getAttribute("token").toString();


            // usiamo i dati di antonio per richiedere gli eventi
            String appId = "770233642";
            String userToken = "221957824499054|efe92043424214df0b1fc809.1-770233642|PkdKbtvJA751W80Mv2SAoOQiujM";
            String eventEidSponsored = sponsoredEventManager.getAllSponsoredEvent();
            System.err.println("Lista eid: " + eventEidSponsored);
            FacebookClient facebookClientApp = new DefaultFacebookClient(userToken);

            String querySponsored = "SELECT eid, name, location, venue FROM event WHERE eid IN "
                    + "(" + eventEidSponsored + ")";

            List<JsonObject> sponsoredResults = facebookClientApp.executeQuery(querySponsored, JsonObject.class);
            System.err.println("Lista eid eventi sponsorizzati: ---->" + eventEidSponsored);

            // per ogni utente del db dobbiamo fare l'accesso con il token
            // per ogni utente possiamo fare la query sui suoi amici
            List<FBuser> users = FBuserManager.findAllFBuser();

            List<JsonObject> queryResults = new LinkedList<JsonObject>();
            List<JsonObject> partialResults = new LinkedList<JsonObject>();
            String query = null;


            FacebookClient facebookClient = new DefaultFacebookClient(accessToken);
            // lista di amici
            Connection<User> friends = facebookClient.fetchConnection(userId + "/friends", User.class);

            String UserIDs = "";
            int i = 0;
            for (User friend : (friends.getData())) {
                if (i < 50) {
                    UserIDs = UserIDs + (String) friend.getId() + ", ";
                    i++;
                }
            }
            UserIDs = UserIDs + userId;

            query = "SELECT eid, name, location, venue, start_time FROM event WHERE eid IN "
                    + "(SELECT eid FROM event_member WHERE uid IN (" + UserIDs + ") )"
                    + "AND (venue.city <> '' OR venue.street <> '' )";

            System.err.println(">>>" + sd.getTime() + "<<<<");

            if (!"".equals(startDate) && sd != null) {
                query += " AND (start_time >= " + (sd.getTime() / (1000)) + ") ";
            }
            if (!"".equals(endDate) && ed != null) {
                query += "AND (start_time <= " + (ed.getTime() / (1000)) + ") ";
            }
//                if(city != "")
//                    query += "AND ( strpos(venue.city, "+city+") >=0 ) ";

            partialResults = facebookClient.executeQuery(query, JsonObject.class);


            for (JsonObject result : partialResults) {

                if (!queryResults.contains(result)) {
                    queryResults.add(result);
                }
            }


            String ResFinal = sponsoredResults.toString() + ";" + queryResults.toString();
            out.print(ResFinal);
            out.flush();
            //}

        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    public Boolean equals(JsonObject A, JsonObject B) {
        return true;
    }

    public boolean equals(Object o, Object u) {
        return (this.toString().equals(((JsonObject) o).toString()));
    }
}
